package com.niiwoo.civet.user.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.Stream;

public class SMSTemplateExtend {

    /**
     * 短信模板前缀映射
     */
    private static final Map<String, SMSTemplatePrefix> MAP = new HashMap<>();

    static {
        MAP.put(formatKey(ProjectType.CARD_EASY_LOAN, ProjectFrom.CARD_NIU), SMSTemplatePrefix.CARD_NIU);
    }

    /**
     * @param projectType 标的类型
     * @param projectFrom 标的来源
     * @param baseTpl     基础短信模板
     * @return
     */
    public static Optional<SMSTemplateKeyEnum> get(byte projectType, byte projectFrom, SMSTemplateKeyEnum baseTpl) {
        ProjectType type = ProjectType.of(projectType).orElseThrow(() -> new NoSuchElementException("projectType=" + projectType));
        ProjectFrom from = ProjectFrom.of(projectFrom).orElseThrow(() -> new NoSuchElementException("projectFrom=" + projectFrom));
        SMSTemplatePrefix smsTemplateExtendPrefix = MAP.get(formatKey(type, from));
        // 没有映射关系，则使用默认模板
        if (smsTemplateExtendPrefix == null) {
            return Optional.of(baseTpl);
        }
        // 根据前缀获取扩展的短信模板Key
        return SMSTemplateKeyEnum.of(smsTemplateExtendPrefix.concatTpl(baseTpl));

    }

    private static String formatKey(ProjectType t, ProjectFrom f) {
        return String.format("%s_%s", t.name(), f.name());
    }


    /**
     * 标的类型
     */
    @Getter
    @AllArgsConstructor
    public enum ProjectType {

        PERSONAL_TOP_SPEED_LOAN((byte) 1, "个人极速借"),
        ENTERPRISE_TOP_SPEED_LOAN((byte) 2, "机构极速借"),
        NIIWOO_CLOUD_LOAN((byte) 3, "你我云贷"),
        CARD_EASY_LOAN((byte) 4, "卡易借");

        private Byte value;
        private String desc;

        public static Optional<ProjectType> of(byte value) {
            return Stream.of(ProjectType.values()).filter(t -> t.getValue() == value).findFirst();
        }

    }

    /**
     * 标的来源
     */
    @Getter
    @AllArgsConstructor
    public enum ProjectFrom {

        APP((byte) 1, "APP"),
        H5_ACTIVITY((byte) 2, "H5活动"),
        H5_TOP_SPEED_LOAN((byte) 3, "H5极速借"),
        RONG_360((byte) 4, "融360"),
        CARD_NIU((byte) 5, "卡牛");

        private Byte value;
        private String desc;

        public static Optional<ProjectFrom> of(byte value) {
            return Stream.of(ProjectFrom.values()).filter(t -> t.getValue() == value).findFirst();
        }

    }

}
